<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的相册集</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .albums-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            grid-gap: 25px;
        }

        .album-card {
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
            text-decoration: none;
            color: inherit;
            display: block;
            position: relative;
        }

        .album-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .album-cover {
            height: 220px;
            overflow: hidden;
            position: relative;
            background-color: #eee;
        }

        .album-cover img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.5s;
        }

        .album-card:hover .album-cover img {
            transform: scale(1.05);
        }

        .album-info {
            padding: 15px;
        }

        .album-name {
            margin: 0 0 5px 0;
            font-size: 18px;
            color: #333;
        }

        .album-count {
            margin: 0;
            color: #777;
            font-size: 14px;
        }

        .no-albums {
            text-align: center;
            padding: 50px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            grid-column: 1 / -1;
        }

        .instructions {
            background-color: #fff9e6;
            border-left: 4px solid #ffcc00;
            padding: 15px;
            margin-bottom: 25px;
            border-radius: 4px;
        }

        .current-dir {
            text-align: center;
            margin-bottom: 20px;
            padding: 10px;
            background-color: #e8f4ff;
            border-radius: 4px;
            color: #333;
        }

        .delete-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: rgba(255, 0, 0, 0.7);
            color: white;
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            font-size: 16px;
            z-index: 10;
            transition: background-color 0.3s;
        }

        .delete-btn:hover {
            background-color: rgb(255, 0, 0);
        }

        .flash-message {
            padding: 10px 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            text-align: center;
        }

        .flash-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .flash-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 20px;
            border-radius: 8px;
            width: 80%;
            max-width: 500px;
            text-align: center;
        }

        .modal-buttons {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            gap: 10px;
        }

        .modal-button {
            padding: 8px 20px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
        }

        .confirm-button {
            background-color: #dc3545;
            color: white;
        }

        .cancel-button {
            background-color: #6c757d;
            color: white;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>我的相册集</h1>

    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            {% for category, message in messages %}
                <div class="flash-message flash-{{ category }}">
                    {{ message }}
                </div>
            {% endfor %}
        {% endif %}
    {% endwith %}

    <div class="instructions">
        <p>在相册目录下创建文件夹，每个文件夹代表一个相册。将图片放入对应的相册文件夹中即可显示。</p>
        <p>相册跟目录：{{ album_dir }}</p>
    </div>

    <div class="albums-grid">
        {% if albums %}
            {% for album in albums %}
                <div class="album-card" data-album-name="{{ album.name }}">
                    <a href="{{ url_for('view_album', album_name=album.name) }}">
                        <div class="album-cover">
                            <img src="{{ url_for('custom_static',albumname=album.name, filename=album.cover) }}" alt="{{ album.name }}">
                        </div>
                        <div class="album-info">
                            <h3 class="album-name">{{ album.name }}</h3>
                            <p class="album-count"><span class="count-value">{{ album.image_count }}</span> 张图片<span class="loading-indicator" style="display: {{ 'inline' if album.image_count == 0 else 'none' }}">...</span></p>
                        </div>
                    </a>
                    <button class="delete-btn" onclick="showDeleteConfirm('{{ album.name }}')">×</button>
                </div>
            {% endfor %}
        {% else %}
            <div class="no-albums">
                <p>暂无相册。请在相册目录下创建相册文件夹并添加图片。</p>
            </div>
        {% endif %}
    </div>
</div>

<!-- 删除确认模态框 -->
<div id="deleteModal" class="modal">
    <div class="modal-content">
        <h3>确认删除</h3>
        <p>您确定要删除相册 "<span id="albumNameToDelete"></span>" 吗？</p>
        <p style="color: #dc3545;"><strong>警告：</strong>这将删除相册文件夹及其中的所有文件，此操作无法撤销！</p>
        <div class="modal-buttons">
            <form id="deleteForm" method="POST">
                <button type="submit" class="modal-button confirm-button">确认删除</button>
            </form>
            <button class="modal-button cancel-button" onclick="hideDeleteConfirm()">取消</button>
        </div>
    </div>
</div>

<script>
    function showDeleteConfirm(albumName) {
        document.getElementById('albumNameToDelete').textContent = albumName;
        document.getElementById('deleteForm').action = "/delete_album/" + albumName;
        document.getElementById('deleteModal').style.display = 'block';
    }

    function hideDeleteConfirm() {
        document.getElementById('deleteModal').style.display = 'none';
    }

    // 点击模态框外部时关闭
    window.onclick = function (event) {
        const modal = document.getElementById('deleteModal');
        if (event.target === modal) {
            hideDeleteConfirm();
        }
    }

    // 优化的相册计数加载机制
    class AlbumCountManager {
        constructor() {
            this.retryCount = 0;
            this.maxRetries = 3;
            this.baseDelay = 2000;
            this.albumElements = new Map();
            this.pendingAlbums = new Set();
            this.init();
        }

        init() {
            // 缓存DOM元素
            document.querySelectorAll('.album-card').forEach(card => {
                const albumName = card.dataset.albumName;
                const countElement = card.querySelector('.count-value');
                const loadingIndicator = card.querySelector('.loading-indicator');
                
                this.albumElements.set(albumName, {
                    countElement,
                    loadingIndicator
                });

                // 如果初始计数为0，标记为待更新
                if (countElement.textContent === '0') {
                    this.pendingAlbums.add(albumName);
                }
            });

            // 使用Intersection Observer优化性能
            this.setupIntersectionObserver();
            
            // 开始加载计数
            if (this.pendingAlbums.size > 0) {
                this.startLoadingCounts();
            }
        }

        setupIntersectionObserver() {
            if ('IntersectionObserver' in window) {
                const observer = new IntersectionObserver((entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const albumName = entry.target.dataset.albumName;
                            if (this.pendingAlbums.has(albumName)) {
                                this.loadSingleAlbumCount(albumName);
                            }
                        }
                    });
                }, { rootMargin: '50px' });

                document.querySelectorAll('.album-card').forEach(card => {
                    observer.observe(card);
                });
            }
        }

        async startLoadingCounts() {
            try {
                const response = await fetch('/api/album_counts');
                const data = await response.json();
                
                this.updateAlbumCounts(data);
                
                // 如果还有待更新的相册，使用指数退避重试
                if (this.pendingAlbums.size > 0 && this.retryCount < this.maxRetries) {
                    const delay = this.baseDelay * Math.pow(2, this.retryCount);
                    this.retryCount++;
                    setTimeout(() => this.startLoadingCounts(), delay);
                }
            } catch (error) {
                console.error('获取相册计数时出错:', error);
                this.handleError();
            }
        }

        async loadSingleAlbumCount(albumName) {
            try {
                const response = await fetch(`/api/count_images/${encodeURIComponent(albumName)}`);
                const data = await response.json();
                
                if (data.count > 0) {
                    this.updateSingleAlbumCount(albumName, data.count);
                }
            } catch (error) {
                console.warn(`加载相册 ${albumName} 计数失败:`, error);
            }
        }

        updateAlbumCounts(data) {
            Object.entries(data).forEach(([albumName, count]) => {
                if (count > 0) {
                    this.updateSingleAlbumCount(albumName, count);
                }
            });
        }

        updateSingleAlbumCount(albumName, count) {
            const elements = this.albumElements.get(albumName);
            if (elements) {
                elements.countElement.textContent = count;
                if (elements.loadingIndicator) {
                    elements.loadingIndicator.style.display = 'none';
                }
                this.pendingAlbums.delete(albumName);
            }
        }

        handleError() {
            if (this.retryCount < this.maxRetries) {
                const delay = this.baseDelay * Math.pow(2, this.retryCount);
                this.retryCount++;
                setTimeout(() => this.startLoadingCounts(), delay);
            } else {
                // 最大重试次数后，隐藏所有加载指示器
                this.albumElements.forEach(elements => {
                    if (elements.loadingIndicator) {
                        elements.loadingIndicator.style.display = 'none';
                    }
                });
            }
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        new AlbumCountManager();
    });
</script>
</body>
</html> 